﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace FileDuplicateRemover.Core
{
    public class EntityTreeBuilder : IDisposable
    {
        private string RootPath { get; set; }

        public EntityTreeBuilder(string rootPath)
        {
            this.RootPath = rootPath;
        }

        public DirectoryEntity Create()
        {            
            DirectoryEntity de = new DirectoryEntity(RootPath);

            CreateCore(de);

            return de;
        }

        private void CreateCore(DirectoryEntity rootDirectoryEntity)
        {
            foreach (string fullFileName in Directory.EnumerateFiles(rootDirectoryEntity.FulltName))
            {
                FileEntity fe = new FileEntity(fullFileName);

                Add(rootDirectoryEntity, fe);
            }

            foreach (string fullDirectoryName in Directory.EnumerateDirectories(rootDirectoryEntity.FulltName))
            {
                DirectoryEntity de = new DirectoryEntity(fullDirectoryName);

                CreateCore(de);

                Add(rootDirectoryEntity, de);
            }
        }

        protected virtual void AddCore(DirectoryEntity directoryEntity, BaseEntity e)
        {
            directoryEntity.EntityList.Add(e);
            directoryEntity.Length += e.Length;
        }

        protected virtual void Add(DirectoryEntity directoryEntity, FileEntity fe)
        {
            FileInfo fi = new FileInfo(fe.FulltName);
            fe.Length = fi.Length;

            AddCore(directoryEntity, fe);

            directoryEntity.TotalEntityCount++;
        }

        protected virtual void Add(DirectoryEntity directoryEntity, DirectoryEntity de)
        {
            AddCore(directoryEntity, de);

            directoryEntity.TotalEntityCount += de.TotalEntityCount;
        }

        public void Dispose()
        {
        }
    }
}
